﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace ThereforeSystems.Samples.Google.UrlShortener
{
    /// <summary>
    /// Helper class which can perform HTTP GET
    /// and HTTP POST operations.
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// Performs a Http Get operation.
        /// </summary>
        /// <param name="url">A valid Url.</param>
        /// <returns>Response from server</returns>
        public static string HttpGET(string url)
        {
            using (WebClient web = new WebClient())
            {
                string response = web.DownloadString(url);
                return response;
            }
        }


        /// <summary>
        /// Posts data to the specified URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="data">The data.</param>
        /// <returns>Response from server</returns>
        /// <remarks>Code here helped in writing this method
        /// http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
        /// </remarks>
        public static string HttpPOST(string url, string data)
        {
            string responseData;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            byte[] byteData = Encoding.UTF8.GetBytes(data);
            request.ContentLength = byteData.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(byteData, 0, byteData.Length);
                stream.Close();
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream dataStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        responseData = reader.ReadToEnd();
                    }
                }
            }

            return responseData;
        }
    }
}
